package org.sourcecode.common.utils;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sourcecode.common.secure.StringXssEditor;

public class QueryUtil {

	public static String mapToUrl(Map<String, String> params, String encoding)
			throws UnsupportedEncodingException {
		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;

		for (String key : params.keySet()) {
			if (StringUtils.isEmpty(key)) {
				continue;
			}
			String value = params.get(key);
			if (StringUtils.isEmpty(value)) {
				value = "";
			}
			if (isFirst) {
				sb.append(key);
				sb.append('=');
				sb.append(URLEncoder.encode(value, encoding));
				isFirst = false;
			} else {
				sb.append("&");
				sb.append(key);
				sb.append('=');
				sb.append(URLEncoder.encode(value, encoding));
			}
		}

		return sb.toString();
	}


	public static Map<String, String> queryToMap(String query, String encoding)
			throws UnsupportedEncodingException {
		Map<String, String> map = new HashMap<String, String>();

		if (StringUtils.isEmpty(query)) {
			return map;
		}
		query = URLDecoder.decode(query, encoding);
		query = query.trim();

		if (query.startsWith("?")) {
			query = query.substring(1);
		}
		String[] params = query.split("&");
		for (String param : params) {
			if (StringUtils.isEmpty(param)) {
				continue;
			}
			String[] paramKeyValue = param.split("=");
			if (paramKeyValue.length != 2) {
				continue;
			}
			String name = paramKeyValue[0];
			if (StringUtils.isEmpty(name)) {
				continue;
			}
			String value = paramKeyValue[1];
			value = StringXssEditor.filterXssWithWhitelist(value);
			map.put(name, value);
		}

		return map;
	}
	
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.out.println( StringEscapeUtils.escapeHtml("<script>alert(1);</script>"));
	}
}